<template>
  <div class="profile">
    <el-card class="profile-card">
      <div slot="header" class="profile-header">
        <el-avatar :src="formData.avatar" size="large"></el-avatar>
        <div class="profile-name">{{ name }}</div>
      </div>
      <div class="profile-body">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="个人资料">
            <el-form :model="formData" ref="form" label-width="100px">
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="formData.nickname"></el-input>
              </el-form-item>
              <el-form-item label="头像" prop="cover">
                <ImageUpload v-model="formData.avatar"/>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="formData.mobile" disabled></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-select v-model="formData.sex" placeholder="选择性别">
                  <el-option v-for="item in sexList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input v-model="formData.age"></el-input>
              </el-form-item>
              <el-form-item label="签名" prop="sign">
                <el-input v-model="formData.sign" clearable="true"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm">保存</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="我的订单">
            <el-table :data="orderList" style="width: 100%">
              <el-table-column label="订单号" align="center" prop="orderNo" show-overflow-tooltip/>
              <el-table-column label="课程名称" align="center" prop="courseTitle"/>
              <el-table-column label="订单金额" align="center" prop="totalFee"/>
              <el-table-column label="订单状态" align="center" prop="status">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status===1?'success':'warning'">{{showStatus(scope.row.status)}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="更改密码">
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input type="password" v-model="passwordForm.oldPassword"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input type="password" v-model="passwordForm.newPassword"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input type="password" v-model="passwordForm.confirmPassword"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="editPassword">修改</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import cookie from 'js-cookie'
import ImageUpload from '@/components/ImageUpload'
import {editPwd, editUserInfo, getLoginUserInfo} from '@/api/user'
import {getAllOrder} from "~/api/order";

export default {
  components: {
    ImageUpload,
  },
  data() {
    return {
      activeTab: '1',
      formData: {},
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          {required: true, message: '请输入旧密码', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {validator: this.validateConfirmPassword, trigger: 'blur'}
        ]
      },
      orderList: [
        {name: '视频1', size: '100MB', date: '2021-10-01'},
        {name: '视频2', size: '200MB', date: '2021-10-02'},
        {name: '视频3', size: '300MB', date: '2021-10-03'}
      ],
      sexList: [
        {id: 1, name: '女'},
        {id: 2, name: '男'}
      ],
      name: '游客',
      avatar: ''
    }
  },
  created() {
    //从cookie获取用户信息  cookie中存放的都是str
    let userStr = cookie.get('userInfo')
    if (userStr === undefined || userStr === '') {
      this.formData = {nickname: "游客"}
    } else {
      this.formData = JSON.parse(String(userStr))
      this.name = this.formData.nickname
      this.avatar = this.formData.avatar
      getAllOrder(this.formData.id).then(res => {
        this.orderList = res.data.data
      })
    }
  },
  methods: {
    showStatus(val) {
      return val === 1? '已支付': '未支付';
    },
    //从cookie中获取用户信息
    showInfo() {
      //从cookie获取用户信息  cookie中存放的都是str
      let userStr = cookie.get('userInfo')
      if (userStr === undefined || userStr === '') {
        this.formData = {nickname: "游客"}
      } else {
        this.formData = JSON.parse(String(userStr))
        this.name = this.formData.nickname
        this.avatar = this.formData.avatar
      }
    },
    submitForm() {
      editUserInfo(this.formData).then(res => {
        getLoginUserInfo().then(response => {
          this.loginInfo = response.data.data
          //获取用户信息,存放到cookie里面
          cookie.set("userInfo", JSON.stringify(this.loginInfo), {domain: 'localhost'})
          this.showInfo()
          this.$message.success('保存成功')
        })
      })
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    editPassword() {
      this.$refs['passwordForm'].validate(valid => {
        if (valid) {
          editPwd(this.formData.id, this.passwordForm.oldPassword, this.passwordForm.newPassword).then(res => {
            this.$message.success('修改密码成功')
          })
        }
      })
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
          return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
    }

  }
}
</script>

<style scoped>
.profile {
  display: flex;
  justify-content: center;
  height: 810px;
}

.profile-card {
  width: 800px;
}

.profile-header {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

.profile-name {
  font-size: 24px;
  margin-left: 20px;
}

.profile-body {
  padding: 20px;
}
</style>
